package chattingRoomNIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

public class ChatClientNIO {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel=SocketChannel.open(new InetSocketAddress("127.0.0.1",8888));
        //切换到非阻塞式的客户端
        socketChannel.configureBlocking(false);
        System.out.println("请输入你要发送给服务器的信息");
        //获取控制台的输入的信息
        Scanner scanner=new Scanner(System.in);
        //3.分配指定大小的缓冲区
        ByteBuffer sendMessageBuf = ByteBuffer.allocate(1024);
        while (scanner.hasNext()){
            String message = scanner.nextLine();
            sendMessageBuf.put(message.getBytes());
            //对缓冲区进行复位
           sendMessageBuf.flip();
            //将控制台的信息发到服务器端
            socketChannel.write(sendMessageBuf);
            //将缓冲区清空
            sendMessageBuf.clear();
        }
        //关闭资源
        scanner.close();
        socketChannel.close();
    }
}
